<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="供应商名称">
                            <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="激活状态">
                            <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="已激活" :value="1" />
                                <el-option label="未激活" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="search-buttons">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="!selectedRows.length"
                        @click="handleBatchDelete">删除</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange"
                style="width: 100%">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" label="序号" width="55" align="center" />
                <!-- <el-table-column prop="enterpriseWechatConfigId" label="配置编号" align="center" /> -->
                <el-table-column prop="supplierName" label="供应商名称" align="center" />
                <el-table-column prop="appSecret" label="应用密钥" align="center" show-overflow-tooltip />
                <el-table-column prop="agentId" label="自建应用ID" align="center" />
                <el-table-column prop="corpId" label="企业应用ID" align="center" />
                <el-table-column prop="isActive" label="激活状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isActive === 1 ? 'success' : 'danger'">
                            {{ row.isActive === 1 ? '已激活' : '未激活' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="180">
                    <template #default="{ row }">
                        <el-button type="text" icon="Edit" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @closed="resetForm">
            <el-form ref="configForm" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="配置编号" prop="enterpriseWechatConfigId" v-if="dialog.isEdit">
                    <el-input v-model="form.enterpriseWechatConfigId" disabled />
                </el-form-item>
                <el-form-item label="供应商" prop="supplierId">
                    <el-select v-model="form.supplierId" placeholder="请选择供应商" clearable>
                        <el-option v-for="item in supplierTypeOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="应用密钥" prop="appSecret">
                    <el-input v-model="form.appSecret" type="password" placeholder="请输入应用密钥" show-password />
                </el-form-item>
                <el-form-item label="自建应用ID" prop="agentId">
                    <el-input v-model="form.agentId" placeholder="请输入自建应用ID" />
                </el-form-item>
                <el-form-item label="企业应用ID" prop="corpId">
                    <el-input v-model="form.corpId" placeholder="请输入企业应用ID" />
                </el-form-item>
                <el-form-item label="激活状态" prop="isActive">
                    <el-switch v-model="form.isActive" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import {
    listEnterpriseWechatConfig,
    getEnterpriseWechatConfig,
    addEnterpriseWechatConfig,
    updateEnterpriseWechatConfig,
    deleteEnterpriseWechatConfig,
    exportEnterpriseWechatConfig,
    getSupplierTypeDict
} from '@/api/basic/message/wechat.js'
const supplierTypeOptions = ref([])
const showSearch = ref(true)

// 数据状态
const loading = ref(false)
const configList = ref([])
const total = ref(0)
const selectedRows = ref([])
const configForm = ref();
// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    supplierName: '',
    isActive: ''
})

// 表单数据
const form = reactive({
    enterpriseWechatConfigId: undefined,
    supplierName: '',
    appSecret: '',
    agentId: '',
    corpId: '',
    isActive: 1,
    supplierId: ''
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: '',
    isEdit: false
})

// 表单验证规则
const rules = reactive({
    supplierId: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' }
    ],
    appSecret: [
        { required: true, message: '请输入应用密钥', trigger: 'blur' }
    ],
    agentId: [
        { required: true, message: '请输入自建应用ID', trigger: 'blur' }
    ],
    corpId: [
        { required: true, message: '请输入企业应用ID', trigger: 'blur' }
    ]
})

// 获取配置列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listEnterpriseWechatConfig(queryParams)
        configList.value = res.rows || [];
        total.value = res.total || 0;
    } catch (error) {
        console.error('获取配置列表失败:', error)
        ElMessage.error('获取配置列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.supplierName = ''
    queryParams.isActive = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.enterpriseWechatConfigId)
}

// 新增配置
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增企业微信配置'
    dialog.isEdit = false
}

// 编辑配置
const handleEdit = async (row) => {
    try {
        const res = await getEnterpriseWechatConfig(row.enterpriseWechatConfigId)
        Object.assign(form, res.data);
        dialog.visible = true
        dialog.title = '编辑企业微信配置'
        dialog.isEdit = true
    } catch (error) {
        console.error('获取配置详情失败:', error)
        ElMessage.error('获取配置详情失败')
    }
}

// 删除配置
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteEnterpriseWechatConfig(row.enterpriseWechatConfigId)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteEnterpriseWechatConfig(selectedRows.value.join(','))
            ElMessage.success('批量删除成功')
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 导出Excel
const handleExport = async () => {
    try {
        await exportEnterpriseWechatConfig(queryParams)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 重置表单
const resetForm = () => {
    Object.assign(form, {
        enterpriseWechatConfigId: undefined,
        supplierName: '',
        appSecret: '',
        agentId: '',
        corpId: '',
        isActive: 1
    })
}

// 提交表单
const submitForm = async () => {
    configForm.value.validate(async valid => {
        if (valid) {
            try {
                if (dialog.isEdit) {
                    await updateEnterpriseWechatConfig(form)
                    ElMessage.success('修改成功')
                } else {
                    await addEnterpriseWechatConfig(form)
                    ElMessage.success('新增成功')
                }
                dialog.visible = false
                getList()
            } catch (error) {
                console.error('操作失败:', error)
                ElMessage.error('操作失败')
            }
        }
    })

}
// 获取供应商类型选项
const getSupplierTypeOptions = async () => {
    try {
        const res = await getSupplierTypeDict()
        supplierTypeOptions.value = res.data;
    } catch (error) {
        console.error('获取供应商类型失败:', error)
    }
}
getSupplierTypeOptions();
// 初始化
onMounted(() => {
    getList()
})
</script>

<style scoped>
.search-card :deep(.el-form-item) {
    margin-bottom: 0px;
}

.search-card {
    margin-bottom: 20px;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>